package zhongbo.javaweb.instagram.web.websocket;

import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zhongbo.javaweb.instagram.service.WebSocketService;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 说明：WebSocket原生实现
 *
 * @author 钟波notebook
 * @see <a href="https://blog.csdn.net/moshowgame/article/details/80275084">SpringBoot2.0集成WebSocket，实现后台向前端推送信息</a>
 * @since 2020年02月03日 星期一 00:40:34
 */
@ServerEndpoint(value = "/websocket")
@Component
@Slf4j
@EqualsAndHashCode
public class WebSocket {

    /**
     * WebSocket 是每次新建对象;这里用Component构造方法静态挂一个service
     */
    private static WebSocketService webSocketService;

    /**
     * 在线人数
     */
    private static volatile AtomicInteger onlineCount = new AtomicInteger();

    /**
     * WebSocket 对象
     */
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    private Session session;

    /**
     * 需保留一个无参构造,提供给ServerEndpointExporter每次创建WebSocket的实例
     */
    public WebSocket() {
    }

    @Autowired
    public WebSocket(WebSocketService webSocketService) {
        WebSocket.webSocketService = webSocketService;
    }

    /**
     * 建立连接
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        int count = WebSocket.onlineCount.incrementAndGet();
        log.info("id: {} 有一连接加入！当前在线人数为: {}", Integer.valueOf(session.getId(), 16), count);
    }


    /**
     * 关闭连接
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        int count = WebSocket.onlineCount.decrementAndGet();
        log.info("id: {} 有一连接关闭！当前在线人数为: {}", Integer.valueOf(session.getId(), 16), count);
    }

    /**
     * 客户端发送消息
     *
     * @param message 消息内容
     * @param session session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (webSocketService.updateMessage(message, session)) {
            return;
        }
        log.info("id: " + Integer.valueOf(session.getId(), 16) + " 来自客户端的消息:" + message);
        // 消息返还给客户端
        sendMessage(session, message);
    }

    /**
     * 错误处理
     *
     * @param session session
     * @param error   error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("id: {} got a error: {}", Integer.valueOf(session.getId(), 16), error.getMessage());
    }

    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     *
     * @param message websocket 消息内容
     * @throws IOException 发送消息异常信息
     */
    public static void sendInfo(String message) throws IOException {
        if (webSocketSet.size() == 0) {
            log.debug("无webSocket链接,不发送通知");
        }
        for (WebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                log.warn("sendInfo error: ", e);
                throw e;
            }
        }
    }

    /**
     * 指定发送消息
     *
     * @param session session
     * @param message msg
     */
    private static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("消息发送失败, msg:{} 失败原因:{}", message, e);
        }
    }

    /**
     * 指定发送消息
     *
     * @param sessionId id
     * @param message   msg
     */
    public static void sendMessage(String sessionId, String message) {
        for (WebSocket webSocket : webSocketSet) {
            if (webSocket.session.getId().equalsIgnoreCase(sessionId)) {
                sendMessage(webSocket.session, message);
                break;
            }
        }
    }

}
